package io.renren.modules.dangan.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.ObjectUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.dangan.dao.DaJnmlbDao;
import io.renren.modules.dangan.dao.DaServerDao;
import io.renren.modules.dangan.dao.DaWsDao;
import io.renren.modules.dangan.entity.DaJnmlbEntity;
import io.renren.modules.dangan.entity.DaServerEntity;
import io.renren.modules.dangan.service.DaJnmlbService;
import io.renren.modules.dangan.utils.DanganConstant;
import io.renren.modules.dangan.utils.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Map;

import static io.renren.common.utils.Constant.UUID;


@Service("daJnmlbService")
public class DaJnmlbServiceImpl extends ServiceImpl<DaJnmlbDao, DaJnmlbEntity> implements DaJnmlbService {

    @Autowired
    private DaJnmlbDao daJnmlbDao;
    @Autowired
    private DaServerDao daServerDao;
    @Autowired
    private DaWsDao daWsDao;
    @CreateCache(name = "tempFile", cacheType = CacheType.LOCAL, localExpire = 1800, localLimit = 100)
    private Cache<String, String> uploadFileTemp;
    @Value("${wsServerId:2}")
    private Integer wsServerId;

    @Value("${upload.jnmlServerXh:13}")
    private Integer uploadJnmlServerXh;

    @Override
    public boolean updateJnmlFile(Map<String, Object> params) {

        try {
            String uuid = params.get(UUID).toString();
            String srcPath = uploadFileTemp.get(uuid);
            if (!params.containsKey("jnmlbh")) {
                insertJnml(params, srcPath);
            }
            Integer jnmlbh = Integer.parseInt(params.getOrDefault("jnmlbh", "0").toString());
            if (StringUtils.isEmpty(srcPath) || jnmlbh == 0) {
                return false;
            }
            DaJnmlbEntity daJnmlbEntity = daJnmlbDao.selectById(jnmlbh);
            if (ObjectUtil.isNull(daJnmlbEntity)) {
                return false;
            }
            DaServerEntity daServerEntity = daServerDao.selectById(daJnmlbEntity.getServerxh());
            String oldJnmlPath = FileUtils.buildFilePath(daServerEntity, daJnmlbEntity);
            File oldJnmlFile = new File(oldJnmlPath);

            String oldJnmlFileName=oldJnmlFile.getName();
            int loc1=oldJnmlPath.lastIndexOf("/");
            int loc2=oldJnmlPath.lastIndexOf("\\");
            if(loc1>loc2){
                oldJnmlPath=oldJnmlPath.substring(0,loc1+1);
            }else{
                oldJnmlPath=oldJnmlPath.substring(0,loc2+1);
            }
            File uploadFile=new File(srcPath);
            File targetFile = new File(oldJnmlPath+uploadFile.getName());
            FileUtil.copy(uploadFile, targetFile, true);
            daJnmlbEntity.setLjmc(daJnmlbEntity.getLjmc().replace(oldJnmlFileName,uploadFile.getName()));
            daJnmlbDao.updateById(daJnmlbEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean saveJnmlFile(DaJnmlbEntity daJnmlbEntity, String uploadJnmlFilePath) {
        try {
            File srcFile=new File(uploadJnmlFilePath);
            List<DaJnmlbEntity> daJnmlbEntities = daJnmlbDao.selectList(new QueryWrapper<DaJnmlbEntity>().eq("nbxh", daJnmlbEntity.getNbxh())
                    .isNotNull("ljmc"));
            String uploadPath=null;
            DaJnmlbEntity  jnmlbEntity=this.getById(daJnmlbEntity.getJnmlbh());
            String ljmc=null;
            if(CollectionUtil.isEmpty(daJnmlbEntities)){
                DaServerEntity daServerEntity = daServerDao.selectOne(new QueryWrapper<DaServerEntity>().eq("serverxh", uploadJnmlServerXh));
                uploadPath=FileUtils.buildFilePath(daServerEntity)+FileUtils.getFilePath()+jnmlbEntity.getNbxh()+File.separator;
                ljmc=FileUtils.getFilePath()+jnmlbEntity.getNbxh()+File.separator+srcFile.getName();
                jnmlbEntity.setServerxh(uploadJnmlServerXh);
            }else{
                DaServerEntity daServerEntity = daServerDao.selectOne(new QueryWrapper<DaServerEntity>().eq("serverxh", daJnmlbEntities.get(0).getServerxh()));
                uploadPath = FileUtils.getFileFtpPathJnml(daServerEntity, daJnmlbEntities.get(0));
                ljmc=FileUtils.getJnmlFilePath(daJnmlbEntities.get(0))+srcFile.getName();
                daJnmlbEntity.setServerxh(daJnmlbEntities.get(0).getServerxh());
//                uploadPath = DanganConstant.uploadJnmlPath+FileUtils.getFilePath()+jnmlbEntity.getNbxh()+File.separator;
//                ljmc=DanganConstant.uploadJnmlPath+FileUtils.getFilePath()+jnmlbEntity.getNbxh()+srcFile.getName();
            }
            File destFile=new File(uploadPath+srcFile.getName());
            if(!destFile.getParentFile().exists()){
                destFile.getParentFile().mkdirs();
            }
            FileUtil.move(srcFile,destFile,true);
            jnmlbEntity.setLjmc(ljmc);
            jnmlbEntity.setMlqx("4");
            this.updateById(jnmlbEntity);
        } catch (IORuntimeException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void insertJnml(Map<String, Object> params, String srcPath) {
        File srcFile = new File(srcPath);
        String filePath = FileUtils.getFilePath() + srcFile.getName();
        DaJnmlbEntity daJnmlbEntity = new DaJnmlbEntity();
        daJnmlbEntity.setNbxh(params.get("nbxh").toString());
        daJnmlbEntity.setMlmc(params.get("bt").toString());
        daJnmlbEntity.setMlbh(1);
        daJnmlbEntity.setMlqx("4");
        daJnmlbEntity.setServerxh(wsServerId);
        daJnmlbEntity.setLjmc(filePath);
        daJnmlbDao.insert(daJnmlbEntity);
        params.put("jnmlbh", daJnmlbEntity.getJnmlbh());
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Integer jnmlbh = (Integer) params.get("jnmlbh");
        String nbxh = (String) params.get("nbxh");
        IPage<DaJnmlbEntity> page = this.page(
                new Query<DaJnmlbEntity>().getPage(params),
                new QueryWrapper<DaJnmlbEntity>()
                        .eq(StringUtils.isNotBlank(nbxh), "nbxh", nbxh)
                        .eq(ObjectUtil.isNotEmpty(jnmlbh), "jnmlbh", jnmlbh)
                        .orderByAsc("mlbh")
        );
        return new PageUtils(page);
    }
}
